package com.ssh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.ssh.domain.Product;
import com.ssh.service.ProductService;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by H-209-FX-XY on 2018/4/10.
 */
@Controller()//用于标注控制层组件（如struts中的action）
@Scope("prototype")//多列模式
@ParentPackage("custom-interceptor")
@Namespace("/")
@InterceptorRef(value = "productInterceptor")
/*    Results({}):集合，对应的结果有多个
 *     Result():一个结果
 *  name:Action return返回的值
 *  location:返回结果的页面
 */
@Results({
        @Result(name="input",location="/hello.jsp"),
        @Result(name="success",location="/hello.jsp"),
//        @Result(name="login",location="/login.jsp"),
//        @Result(name="register",location="/register.jsp")
})
public class ProductAction extends ActionSupport implements ModelDriven<Product>{
    /**模型驱动使用类*/
    private Product product;
    private List<Product> productList = new ArrayList<>();
    @Override
    public Product getModel() {
        return product;
    }
    /**Struts和Spring整合过程中按名称自动注入的业务层类*/
    @Autowired
    private ProductService productService;

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    @Action("save")
    public String save(){
        if(product!= null) System.out.println(product.toString());
        productService.save(product);
        productList = productService.findAll();
        return "success";
    }

    @Action("list")
    public String list(){
        if(product!= null) System.out.println(product.toString());
        productList = productService.findAll();
        return "success";
    }

    /**
     * 效验save
     */
    public void validateSave() {
        if(product != null && product.getPname().isEmpty()){
            addFieldError("product.pname","名字不能为空");
            System.out.println("名字不能为空");
        }
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public List<Product> getProductList() {
        return productList;
    }

    public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

    public ProductService getProductService() {
        return productService;
    }
}
